function [outarray] = struct_extract(struct, substruct, field, list)
% struct_extract : extract data that is in a substructure
% from the control structure and return it in the outarray
% 12/3/98 P. Manis
% for example: dvmax = struct_extract(CONTROL, spike, dvmax, selrecs)
% would return in dvmax all of the dvmax elements of the spike substructure
% of CONTROL that are in CONTROL(selrecs).spike.dvmax. Note that MATLAB
% doesn't let you access the structure in this way with an array as selrecs..
% example 2: struct_extract(CONTROL, spike, [], list) would return
% just the CONTROL(list).spike data (assumes there is no further data...)
% 3/29/99 P. Manis
% modified to return according to the data type in the field


outarray={}
if(isempty(list))
   return;
end;
k = 1;
for i=list
   if(~isempty(field))
      ptr = sprintf('struct(i).%s.%s', substruct, field); % point to deeper element
   else
      ptr = sprintf('struct(i).%s', substruct); % no deeper structure element
   end
   p2 = sprintf('struct(i).%s', substruct);
   if(~isempty(eval(p2)))
      d = eval(char(ptr));
      if(isstruct(d))
         outarray{k} = d;
      end
      if(isnumeric(d))
         if(length(d) == 1)
            outarray{k}=d;
         else
            if(k == 1)
               m = size(list);
               outarray=zeros(m(2), 1);
            end
            l = size(outarray);
            dl = length(d);
            if(l(2) > dl)
               d(dl+1: l(2)) = NaN;
            end
            dl=length(d);
            [m n] = size(d);
            if(m > n) d = d'; % these are supposed to be arrays, but some are stored rotated...
            end
            %            disp(sprintf('i: %d  l: %d  dl: %d', i, l, dl))
            outarray{k,1:dl} = d;
            
         end
      end
      if(ischar(d))
         outarray{k} = {d};
      end
      if(isempty(d))
         outarray{k} = [];
      end
      
      k=k+1;
   end
end
% now clean up the returned arrays. No NaN's allowed...
%outarray=outarray(~isnan(outarray));
return;


